package com.yuuzy.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBUtils {
    private static DataSource ds;

    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src/druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //返回连接
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }


    //关闭连接
    public static void close(ResultSet set, Statement stm, Connection conn) {
        try {
            if (set != null) {
                set.close();
            }
            if (stm != null) {
                stm.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

//    public static void main(String[] args) {
//        Connection connection = null;
//        try {
//            connection = DBUtils.getConnection();
//            System.out.println("数据库连接成功");
//
//        } catch (SQLException e) {
//            throw new RuntimeException(e);
//        }
//        finally {
//            DBUtils.close(null,null,connection);
//            System.out.println("数据库关闭成功");
//        }
//    }
}